package net.zoneland.zrdp.common.utils.html;

import org.apache.commons.text.StringEscapeUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Safelist;



/**
 * HTML过滤器，用于去除XSS漏洞隐患。
 *
 * @author zonevue
 */
public final class HtmlXssFilter {

    private static final Cleaner cleaner = new Cleaner(Safelist.none());

    /**
     * Default constructor.
     */
    private HtmlXssFilter() {
        throw new IllegalStateException("Utility class");
    }


    /**
     * 过滤用户输入的HTML内容，去除所有html标签。注意：会把用户输入的 &amp;lt; 等转义成<; (如 a &amp;lt; b 最后结果变成 a < b)
     * <p>Example:</p>
     * <pre>{@code
     *     String sourceBodyHtml = "<p>5 is &lt; 6.</p>";
     *     String html = HtmlXssFilter.filter(sourceBodyHtml);
     *
     *     // html is: 5 is < 6.
     * }</pre>
     * @param dirtyInput 待过滤的HTML内容
     * @return 过滤后的HTML内容
     */
    public static String filter(final String dirtyInput) {
        return cleaner.clean(Jsoup.parse(StringEscapeUtils.unescapeHtml4(dirtyInput))).text();
    }

}
